package com.example.lhh.shiro.cashe;

import com.example.lhh.util.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;

/**
 * @author luoHongHu
 * @Description 自定义cache
 * @date 2025年05月17日 11:08
 */
public class RedisCache<K, V> implements Cache<K, V>{

    private static final Logger log = LoggerFactory.getLogger(RedisCache.class);

    private  String cacheName = "";

    public RedisCache(){}

    public RedisCache(String name){
        this.cacheName = name;
    }

    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        return redisTemplate;
    }

    /**
     * H获取缓存中的值
     * @param k
     * @return
     * @throws CacheException
     */
    @Override
    public V get(K k) throws CacheException {
        log.info("=================获取缓存==================");
        return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
    }

    /**
     * 存放缓存
     * @param k
     * @param v
     * @return
     * @throws CacheException
     */
    @Override
    public V put(K k, V v) throws CacheException {
        log.info("=================存入缓存==================");
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
        return null;
    }

    /**
     * 移除缓存
     * @param k
     * @return
     * @throws CacheException
     */
    @Override
    public V remove(K k) throws CacheException {
        getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
        return null;
    }

    /**
     * 情况缓存
     * @throws CacheException
     */
    @Override
    public void clear() throws CacheException {
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
        return getRedisTemplate().opsForHash().size(cacheName).intValue();
    }


    @Override
    public Set<K> keys() {
        return (Set<K>) getRedisTemplate().opsForHash().keys(cacheName);
    }

    @Override
    public Collection<V> values() {
        return (Collection<V>) getRedisTemplate().opsForHash().values(this.cacheName);
    }
}
